import { normalizeAuthConfig, hasPermission, addComponentHook, addVueCss } from './index.js';
import { h } from 'vue';

/**
 * 使用混入方式实现组件级别控制，支持一下方式配置：
    permission: 'abc',
    permission: ['aaa', 'bbb'],
    permission: {code: ['aaa', 'bbb'], logic: 'or'},
    permission: {code: ['aaa', 'bbb'], class: ['c-2', 'c-3'], style: { width: '40px', height: '20px' }},
    permission: {code: ['aaa', 'bbb'], component: ElSwitch},
 */
function componentPermissionMixin(app){
  app.mixin({
    beforeCreate() {
      let self = this;
      let permission = self.$options.permission;
      if (!permission){
        return;
      }
      let config = normalizeAuthConfig(permission);
      // 验证权限
      if (hasPermission(config.code, config.logic, config.tip)) {
        if (self.$.render != self.$options.render){
          self.$.render = self.$options.render;
        }
        return;
      }
      

      // 是否存在component 则替换组件
      if (config.component) {
        self.$.render = () => h(config.component);
        return;
      }

      let css = config.css;
      if (css.class || css.style) {
        addComponentHook(self.$, 'm', function pushVueCss() {
          addVueCss([self.$.vnode], config.css);
        });
        addComponentHook(self.$, 'u', function pushVueCss() {
          addVueCss([self.$.vnode], config.css);
        });
        return;
      }

      // 移除组件
      self.$.render = () => null;
    }
  });
}

export default {
  install(app) {
    componentPermissionMixin(app);
  }
};